package com.xiaoxing.yunshu.app;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.util.DisplayMetrics;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.trace.LBSTraceClient;
import com.baidu.trace.Trace;
import com.baidu.trace.api.entity.LocRequest;
import com.baidu.trace.api.entity.OnEntityListener;
import com.baidu.trace.api.track.LatestPointRequest;
import com.baidu.trace.api.track.OnTrackListener;
import com.baidu.trace.model.ProcessOption;
import com.jess.arms.base.BaseApplication;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.SharedPreferencesHelper;
import com.xiaoxing.yunshu.R;
import com.xiaoxing.yunshu.mvp.ui.activity.InTransitActivity;
import com.xiaoxing.yunshu.mvp.ui.track.CommonUtil;

import java.util.Locale;
import java.util.concurrent.atomic.AtomicInteger;

import cn.jpush.android.api.JPushInterface;
import me.jessyan.armscomponent.commonsdk.utils.LanguageUtil;

/**
 * @author 小星 QQ:753940262
 * @class describe
 * @time 2018/7/19 0019 8:46
 */
public class MyApplication extends BaseApplication {

    public static int screenWidth = 0;
    public static int screenHeight = 0;
    private static Context mContext;
    public SharedPreferencesHelper trackConf = null;
    /**
     * 轨迹服务ID
     */
    public long serviceId = BaseConstants.SERVICE_ID;
    /**
     * Entity标识
     */
    public String entityName = "myXYWHYunShuTrace";
    public boolean isRegisterReceiver = false;
    /**
     * 服务是否开启标识
     */
    public boolean isTraceStarted = false;
    /**
     * 采集是否开启标识
     */
    public boolean isGatherStarted = false;
    /**
     * 轨迹客户端
     */
    public LBSTraceClient mClient = null;
    /**
     * 轨迹服务
     */
    public Trace mTrace = null;
    private AtomicInteger mSequenceGenerator = new AtomicInteger();
    private Notification notification = null;
    private LocRequest locRequest = null;

    public static Context getContext() {

        return mContext;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();

        JPushInterface.setDebugMode(true);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);            // 初始化 JPush

        entityName = "";
//        entityName = CommonUtil.getImei(this);

        // 若为创建独立进程，则不初始化成员变量
        if ("com.baidu.track:remote".equals(CommonUtil.getCurProcessName(mContext))) {
            return;
        }

        SDKInitializer.initialize(mContext);

//        MobSDK.init(this);
//        initI18();
        getScreenSize();

//        if (isChuKu()) {
        initTrace();
//        }


        clearTraceStatus();
    }

    /**
     * 获取屏幕尺寸
     */
    private void getScreenSize() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        screenHeight = dm.heightPixels;
        screenWidth = dm.widthPixels;
    }

    private void initTrace() {
        initNotification();
        mClient = new LBSTraceClient(mContext);
        mTrace = new Trace(serviceId, entityName);
        mTrace.setNotification(notification);

        trackConf = SharedPreferencesHelper.getInstance(this);

        locRequest = new LocRequest(serviceId);
    }

    /**
     * 清除Trace状态：初始化app时，判断上次是正常停止服务还是强制杀死进程，根据trackConf中是否有is_trace_started字段进行判断。
     * <p>
     * 停止服务成功后，会将该字段清除；若未清除，表明为非正常停止服务。
     */
    private void clearTraceStatus() {
        if (trackConf.contains("is_trace_started") || trackConf.contains("is_gather_started")) {
            trackConf.removeString("is_trace_started");
            trackConf.removeString("is_gather_started");
        }
    }

    private void initNotification() {
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder;
        //判断是否是8.0Android.O
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel chan1 = new NotificationChannel("static", "Primary Channel", NotificationManager.IMPORTANCE_HIGH);
            manager.createNotificationChannel(chan1);
            builder = new NotificationCompat.Builder(this, "static");
        } else {
            builder = new NotificationCompat.Builder(this);
        }
//        Intent notificationIntent = new Intent(this, TracingActivity.class);
        Intent notificationIntent = new Intent(this, InTransitActivity.class);

        Bitmap icon = BitmapFactory.decodeResource(this.getResources(),
                R.drawable.icon_tracing);

        // 设置PendingIntent
        builder.setContentIntent(PendingIntent.getActivity(this, 0, notificationIntent, 0))
                .setLargeIcon(icon)  // 设置下拉列表中的图标(大图标)
                .setContentTitle("百度鹰眼") // 设置下拉列表里的标题
                .setSmallIcon(R.drawable.icon_tracing) // 设置状态栏内的小图标
                .setContentText("服务正在运行...") // 设置上下文内容
                .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间

        notification = builder.build(); // 获取构建好的Notification
        notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
    }

    /**
     * 初始化国际化语言，繁体字和简体字
     */
    private void initI18() {
        Resources resources = getResources();

        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration config = resources.getConfiguration();
        if (LanguageUtil.getCountry(getApplicationContext()).equals("TW")) {

            config.locale = Locale.TAIWAN;

        } else {

            config.locale = Locale.TAIWAN;
        }

        resources.updateConfiguration(config, dm);
    }

    private boolean isChuKu() {
        return trackConf.getBoolean(BaseConstants.IS_CHU_KU);
    }

    /**
     * 获取当前位置
     */
    public void getCurrentLocation(OnEntityListener entityListener, OnTrackListener trackListener) {
        // 网络连接正常，开启服务及采集，则查询纠偏后实时位置；否则进行实时定位
        if (ArmsUtils.isNetworkAvailable(mContext)
                && trackConf.contains("is_trace_started")
                && trackConf.contains("is_gather_started")
                && trackConf.getBoolean("is_trace_started", false)
                && trackConf.getBoolean("is_gather_started", false)) {
            LatestPointRequest request = new LatestPointRequest(getTag(), serviceId, entityName);
            ProcessOption processOption = new ProcessOption();
            processOption.setNeedDenoise(true);
            processOption.setRadiusThreshold(100);
            request.setProcessOption(processOption);
            mClient.queryLatestPoint(request, trackListener);
        } else {
            mClient.queryRealTimeLoc(locRequest, entityListener);
        }
    }

    /**
     * 获取请求标识
     *
     * @return
     */
    public int getTag() {
        return mSequenceGenerator.incrementAndGet();
    }
}
